/**
 * Module based on Libiconv library.
 * This module is used for character encoding conversion
 *
 * Features:
 * - Convert character encoding(Supports mutual conversion of common character encodings such as UTF-8, GBK, and Unicode)
 *
 * Usage:
 * - Use convert() to convert character encoding.
 */
import { iconvClass } from './libvbar-m-dxIconv.so';

let iconvObj = null
const iconv = {};

iconv.FROM_TYPE = {
    STRING: 0,
    ARRAY_BUFFER: 1,
}

iconv.TO_TYPE = {
    ARRAY_BUFFER: 0,
    STRING: 1,
}

/**
 * Character encoding conversion
 * @param {string} fromCharacter Original character encoding
 * @param {string} toCharacter The character encoding to be converted to
 * @param {string} data Converted character data
 * @param {number} fromType Type before conversion
 * @param {number} toType Converted type
 */
iconv.convert = function(fromCharacter, toCharacter, data, fromType = iconv.TYPE.STRING, toType = iconv.TO_TYPE.ARRAY_BUFFER) {

    if (!iconvObj) {
        iconvObj = new iconvClass();
    }

    if (typeof fromCharacter !== 'string' || fromCharacter.length === 0) {
        throw new Error(`fromCharacter must be a non-empty string`);
    }
    if (typeof toCharacter !== 'string' || toCharacter.length === 0) {
        throw new Error(`toCharacter must be a non-empty string`);
    }
    if ((typeof data !== 'string' && typeof data !== 'object') || (typeof data === 'string' && data.length <= 0)) {
        throw new Error(`data must be a non-empty string or object`);
    }
    if(fromType !== iconv.FROM_TYPE.STRING && fromType !== iconv.FROM_TYPE.ARRAY_BUFFER){
        throw new Error(`fromType must be one of iconv.FROM_TYPE.STRING or iconv.FROM_TYPE.ARRAY_BUFFER`);
    }
    if(toType !== iconv.TO_TYPE.ARRAY_BUFFER && toType !== iconv.TO_TYPE.STRING){
        throw new Error(`toType must be one of iconv.TO_TYPE.ARRAY_BUFFER or iconv.TO_TYPE.STRING`);
    }
    return iconvObj.convert(fromCharacter, toCharacter, data, fromType, toType)
}


export default iconv;
